using Godot;
using System;
using Godot.Collections;
using System.Linq;
using System.Collections;
using System.Text.Json;

public partial class sword_ability_controller : Node
{

	[Export]
	public PackedScene SwordAbility;
	[Export]
	public Timer timer;
	
	private float MAX_RANGE = 150;

	int baseDamage = 5;//伤害
	float additionalDamagePercent = 1;

	double baseWaitTime;


	GameEvents gameEvents;//自动加载文件

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		gameEvents = GetNode<GameEvents>("/root/GameEvents");
		timer.Timeout += ()=>{
			this.OnTimerTimout();
		};
		gameEvents.AbilityUpgradeAdded += OnAbilityUpgradeAdded;

		baseWaitTime = timer.WaitTime;
		
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	private void OnTimerTimout(){
		Node2D player = GetTree().GetFirstNodeInGroup("player") as Node2D;
		if(player == null){
			return ;
		}

		Node2D[] enemies = GetTree().GetNodesInGroup("enemy").Select(enemy=>enemy as Node2D) //Select相当于 java中stream.map
		.Where(enemy => { //Where 相当于 java中的stream.filter
			float distance = enemy.GlobalPosition.DistanceSquaredTo(player.GlobalPosition); //DistanceSquaredTo返回的是两点之间距离的平方
			return distance < Math.Pow(MAX_RANGE,2);
		}).OrderBy(enemy => {   //OrderBy从小到大排序  OrderByDescending:从大到小排序
			return enemy.GlobalPosition.DistanceSquaredTo(player.GlobalPosition);
		}).ToArray();

		if(enemies.Length < 1){
			return ;
		}

		SwordAbility swordInstance = SwordAbility.Instantiate() as SwordAbility;
		// player.GetParent().AddChild(swordInstance);
		GetTree().GetFirstNodeInGroup("foreground_layer").AddChild(swordInstance);
		swordInstance.hitboxComponent.damage = this.baseDamage * this.additionalDamagePercent;

		swordInstance.GlobalPosition = enemies[0].GlobalPosition;
		swordInstance.GlobalPosition += Vector2.Right.Rotated((float)(new Random().NextDouble()*Math.PI));
		swordInstance.Rotation = (enemies[0].GlobalPosition - swordInstance.GlobalPosition).Angle();
	}

	public void OnAbilityUpgradeAdded(AbilityUpgrade upgrade,int quantity){
		if(upgrade.id == "sword_rate"){
			double percentReduction = quantity * .1;
			timer.WaitTime = baseWaitTime * (1 - percentReduction);
			timer.Start();
		}else if(upgrade.id == "sword_damage"){
			this.additionalDamagePercent = 1 + (float)(quantity * .15);
		}
	}

	public override void _ExitTree(){
		//gameEvents 为自动加载类，不会销毁，所以绑定在gameEvents上的事件需要再节点退出的时候也要解除事件
		gameEvents.AbilityUpgradeAdded -= OnAbilityUpgradeAdded;
		base._ExitTree();
	}
}
